# -*- coding: utf-8 -*-
# @author: wch
# @file: cut_video_area.py
# @time: 2023/2/1 13:09

import numpy_learn as np
import cv2
import os

"""
    将视频路径传入后，根据指定的坐标点位，剪切其中指定区域，生成新的视频
"""

# 根据传入视频的路径，读取视频，将视频转化为图片,根据传入的坐标剪切图片，保存在指定的文件夹中
def video_to_img(videopath, savepath, tuple01, tuple02):
    cap = cv2.VideoCapture(videopath)
    count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            new_img = frame[tuple01[1]:tuple02[1], tuple01[0]:tuple02[0]]
            cv2.imwrite(savepath + str(count) + ".jpg", new_img)
            count += 1
        else:
            break
    cap.release()


# 将新的图片文件中的文件合成新的视频
def img_to_video(savepath, savepath02):
    files = os.listdir(savepath)
    files.sort(key=lambda x: int(x[:-4]))
    print(files)
    fps = 30
    fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
    video_writer = cv2.VideoWriter(filename=savepath02, fourcc=fourcc, fps=fps,
                                   frameSize=(360, 640))
    for file in files:
        img = cv2.imread("E:\dyk\opencv\media\image" + "\\" + str(file))
        cv2.waitKey(100)
        video_writer.write(img)
    video_writer.release()


# 视频转剪切局部的的视频入口
def main(videopath, savepath, savepath02, tuple01, tuple02):
    video_to_img(videopath, savepath, tuple01, tuple02)
    img_to_video(savepath, savepath02)


if __name__ == '__main__':
    videopath = r"E:\dyk\opencv\media\two_video.mp4"
    savepath = r"E:\dyk\opencv\media\image" + "\\"
    savepath02 = r'E:\dyk\opencv\media\partvideo.avi'
    tuple01 = (0, 0)
    tuple02 = (360, 640)
    main(videopath, savepath, savepath02, tuple01, tuple02)
